<template>
  <div class="form">
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="type == 2 ? '修改方案' : '添加方案'"
      @close="cancel"
    >
      <el-form style="width: 80%" :model="params" :rules="rules" ref="formRef">
        <el-form-item label="方案名称" label-width="100px" prop="scheme_name">
          <el-input
            v-model="params.scheme_name"
            size="mini"
            maxlength="30"
            placeholder="请输入方案名称"
          >
          </el-input>
          <div class="form-tip">提示：最多可输入30位</div>
        </el-form-item>
        <el-form-item label="配送费" label-width="100px" prop="fee">
          <el-input
            v-model="params.fee"
            size="mini"
            type="number"
            maxlength="30"
            placeholder="请输入配送费"
          >
          </el-input>
          <div class="form-tip">提示：请输入纯数字</div>
        </el-form-item>
        <el-form-item label="绑定区域" label-width="100px" prop="relation">
          <el-cascader
            placeholder="请选择绑定区域"
            size="mini"
            v-model="relation"
            :options="areaList"
            :props="areaProps"
            filterable
            :style="{ width: '100%' }"
            @change="areaChange"
          ></el-cascader>
          <div class="form-tip">提示：可多选</div>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button @click="cancel" size="mini">取消</el-button>
        <el-button type="primary" @click="submit" size="mini">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { eraeList } from "@/api/common"
import { store } from "@/api/delivery"
export default {
  name: "my-form",
  data() {
    return {
      type: 1,
      dialogFormVisible: false,
      params: {
        scheme_name: "",
        fee: 0,
        relation: [],
      },
      areaProps: {
        multiple: true,
        checkStrictly: true,
        emitPath: false,
        value: "value",
        label: "area_name",
        expandTrigger: "hover",
        children: "children",
      },
      areaList: [], // 省市列表
      relation: [],
      rules: {
        scheme_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 1, max: 30, message: "请勿超过30位", trigger: "blur" },
        ],
        fee: [{ required: true, message: "请输入配送费", trigger: "blur" }],
        relation: [{ required: true, message: "请选择区域", trigger: "blur" }],
      },
    }
  },
  methods: {
    show(type = 1, row) {
      this.type = type
      this.reset()
      this.getAreaList()
      this.dialogFormVisible = true
      if (type == 2) {
        this.params.scheme_id = row.scheme_id
        this.params.scheme_name = row.scheme_name
        this.params.fee = row.fee
        this.relation = this.tree(row.relation)
        this.params.relation = row.relation
      }
    },
    // 回显处理数据
    tree(data) {
      let result = []
      for (let i = 0; i < data.length; i++) {
        let res = data[i]
        result.push(res.area_id)
      }
      return result
    },
    /**
     * @desc 获取省市列表
     */
    async getAreaList() {
      try {
        const data = await eraeList()
        if (!data.data) {
          return
        }
        const options = data.data.map((item) => {
          return {
            value: item.area_id,
            area_name: item.area_name,
            area_type: 1,
            children: item.child
              ? item.child.map((child) => {
                  return {
                    value: child.area_id,
                    area_name: child.area_name,
                    area_type: 2,
                  }
                })
              : [],
          }
        })
        this.areaList = options
      } catch (ex) {
        console.log(ex)
      }
    },
    areaChange(e) {
      let foundElements = []
      let cache = new Map() // 新增：用于缓存搜索结果
      for (let i = 0; i < e.length; i++) {
        if (foundElements.includes(e[i])) {
          continue
        }
        let foundElement = this.searchItem(this.areaList, e[i], cache) // 修改：传入缓存对象
        if (foundElement) {
          const res = {
            area_id: foundElement.value,
            area_name: foundElement.area_name,
            area_type: foundElement.area_type,
          }
          foundElements.push(res)
        }
      }
      this.params.relation = foundElements
    },
    searchItem(data, id, cache) {
      if (cache.has(id)) {
        // 新增：从缓存中获取搜索结果
        return cache.get(id)
      }
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.value === id) {
          cache.set(id, item) // 新增：将搜索结果缓存
          return item
        } else if (item.children && item.children.length > 0) {
          let result = this.searchItem(item.children, id, cache)
          if (result) {
            cache.set(id, result) // 新增：将搜索结果缓存
            return result
          }
        }
      }
      return undefined
    },
    reset() {
      this.params = {
        scheme_name: "",
        fee: 0,
        relation: [],
      }
      // this.areaList = []
      this.relation = []
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    // 选中省市区
    areaChange(e) {
      let foundElements = []
      let cache = new Map() // 新增：用于缓存搜索结果
      for (let i = 0; i < e.length; i++) {
        if (foundElements.includes(e[i])) {
          continue
        }
        let foundElement = this.searchItem(this.areaList, e[i], cache) // 修改：传入缓存对象
        if (foundElement) {
          const res = {
            area_id: foundElement.value,
            area_name: foundElement.area_name,
            area_type: foundElement.area_type,
          }
          foundElements.push(res)
        }
      }
      this.params.relation = foundElements
    },
    // 取消
    cancel() {
      this.reset()
      this.dialogFormVisible = false
    },
    // 提交
    submit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await store(this.params)
            this.$msg.successMsg(res.msg)
            this.cancel()
            this.$emit("refresh")
          } catch (ex) {
            console.log(ex)
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
